/**
 * 售后订单列表
 * 包含：售后申请和售后退货单
 * 不需要复选框进行批量操作
 */

import React, { Component } from 'react';
import { Relax, msg } from 'iflux2';
import { Table, Row, Col, Button, Popover, Icon ,Popconfirm} from 'antd'
import { Map, OrderedSet, List } from 'immutable'
import classNames from 'classnames'
import { listQL } from '../ql';
import { orderColumns } from '../constant/columns';
import { orderStatus } from '../constant/order-status';
import noop from 'util/noop';
import moment from 'moment'
import { Link } from 'react-router'
import OrderTable from 'components/OrderTable';
import { roleShape } from 'constant/PropTypes.js'
import roleEnum from 'constant/roleEnum.js'
import RefundDialog from '../../component/RefundDialog.js'
import Image from 'components/Image'

import { defaultAvatorImage } from 'constant/image.js'
@Relax
class AfterSalesContainer extends Component {
    static defaultProps = {
        list:listQL,
        filterKey:'',
        filters:List.of(),
        pagination: Map({}),
        loading: true,
        startExportOrder: noop,
        setPagination:noop,
        queryOrderList: noop,//订单过滤条件查询
        setOrderStatus: noop,//设置订单状态（过滤条件）
        resetPagination: noop,//重置分页
        fetchRefundOrderInfo: noop,
        confirmRefund:noop,
        auditOrder:noop,
        cancelOrder:noop,
        receivedGoods:noop,
        type:'',
        refund:Map({}),
        userLogos:Map({})//用户头像，usercode：src

    }

    constructor(props){
        super(props);

        /**
         * false：不通过，拒收，true：通过，收货，退款
         * 每个阶段对应不同的按钮loading状态
         */
        this.auditStatus = '';
        //当前操作的订单
        this.activeRid = ''
        //查看详情的链接地址，会计下的退货单和订单客服下的退货单，退货申请各不同，防止左侧菜单误选中
        this.detailLink = '';
        //页面滚动控制，翻页时调用
        this.pageWrapper = null;
        this.state = {
            // role:{bname:''},
             loading:false,
            //selectedRowKeys: [],
            filterName: '所有退货单',
            filterDropdownVisible: false,//过滤条件下拉框显示
            //filters: [],
            refundVisible:false,//退款确认
            refundOrder:{},
        }
    }


    static contextTypes = {
        role:roleShape
    }
    componentWillReceiveProps(nextProps) {
        //角色不一定在渲染或更新的时候拿到
        if(nextProps.type !== this.props.type || !this.detailLink){
            this.detailLink = `/after/sales/${nextProps.type}/`;
        }
    }
    
    componentDidMount() {
        const { type } = this.props;
       
        this.detailLink = `/after/sales/${type}/`;

        if(window.document.getElementById("react-content")){
            this.pageWrapper = window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0];
        }

         //页面变化滚动到顶部
        msg.on('page_changed',() => {
            this.scrollTop()
        })
    }
    

    render() {

        const { list, loading, pagination } = this.props;
    
        //头部header列，不包含数据
        const orderHeader = (
            <Table 
                pagination={false}
        //        rowSelection={rowSelection}
                columns={this.renderHeaderColumns()}
                dataSource={[]}
                onChange={this.onChangeFilter} 
            />

        );

        const page = {
            current:pagination.get('pageNum'),
            total:pagination.get('totalCount'),
            pageSize:pagination.get('pageSize'),
            onChange:this.changePageNum,
            onShowSizeChange:this.changePageSize,
            showTotal:(total)=>`共${total}条`,
            showQuickJumper: true,
            showSizeChanger: true,
        }

        const {refund} = this.props;
        const {refundVisible, refundOrder } = this.state;
     
        let disabled = false;
        if(refundOrder.tid){
            disabled = list.find((item)=>item.get('tid') === refundOrder.tid).get('needReturn') != 1 ? true : false;
        }
        return (
            <div>
                {/*this.renderToolBar()*/}
                <OrderTable
                    rowKey='applyId'
                    hideKey="itemList"
                    loading={loading}
                    header={orderHeader}
                    rowHeader={this.renderRowHeader}
//                    rowSelection={tableSelection}
                    dataSource={list.toJS()}
                    columns={this.renderSubColumns()}
                    pagination={page}
                />
                <RefundDialog
                    refund={refund}
                    disabled={disabled}
                    visible={refundVisible}
                    onOk={this.confirmRefund}
                    onCancel={this.cancelRefund}
                />
            </div>
        );
    }

    /**
     * 全选操作
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    // selectAll(selected, selectedRows, changeRows) {
    //     let selectedRowKeys = [];
    //     selected && selectedRows.forEach(row => selectedRowKeys.push(row.applyId));
    //     this.setState({ selectedRowKeys });
    // }
     /**
     * 修改订单转测
     * @param pagination 分页参数
     * @param filters   过滤条件
     * @param sorter    排序
     */
    onChangeFilter = (pagination, filters, sorter) => {
        
        this.setState({
            filterName: (orderStatus[filters.filter[0] || 'ALL']),
           // filters: filters.filter
        })
    }
    /**
     * 每行渲染头部回调函数
     * @param object record 
     */
    renderRowHeader = (record) => {
        /**
         * <Checkbox checked={selectedRowKeys.includes(order.get('applyId'))} onChange={() => { selectRow(order.get('applyId')) }} />
         */
        const { filterKey, userLogos } = this.props;

        let key = filterKey;
        if(filterKey === "AUDITED_AFTER" || filterKey === "AUDITED_BEFORE"){
            key = record.orderStatus;
        }
        return (
            <Row>
                <Col span={18}>
                    <div className="buyer-avatar">
                        <Image  width={32}
                                height={32}
                                auto={true}
                                src={userLogos.get(record.usercode) || defaultAvatorImage}
                        />
                    </div>
                    <div className="order-info">
                        <p>
                            <span className="mr10">{`买家：${record.nickname}`}</span>
                            <span className="mr10 t-grayer">{`收货人：${record['consigneeInfo']['consigneeName']}`}</span>
                            <span className="mr10 t-grayer">{record['consigneeInfo', 'consigneeMobile']
                                || record['consigneeInfo', 'consigneePhone']}</span>
                        </p>
                        <p>
                            <span className="mr10">{`退货单号：${record.applyId}`}</span>
                            <span className="mr10">{`订单号：${record.tid}`}</span>
                            <span className="mr10 t-grayer">{`申请时间：${moment(record.ctime).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                        </p>
                    </div>
                </Col>
                <Col span={6}>
                    <div className="t-right">
                        <p className="order-status">{orderStatus[key]}</p>
                        {record.needReturn === 1 ? "售后退货" : "售中退款"}
                    </div>
                </Col>
            </Row>
        )
    }
    /**
     * 渲染toolBar
     * @returns {XML}
     */
    renderToolBar = () => {
        return (
            <Row className="table-toolbar">
                <Col span={12}>
                    <Link to="/order/list/success"><Button type="primary">发起退货申请</Button></Link>
                </Col>
            </Row>
        );
    }

    /**
     * 扩展最后一列
     * @returns {*|{options, browsertest, dist, rhino, rhinolessc}|Buffer|Array.<T>|string}
     */
    renderHeaderColumns() {
        let { filterKey, filters } = this.props;
        let { filterName, filterDropdownVisible } = this.state;
        const _this = this;
        let operation = {
            title: orderStatus[filterKey],
            width: 350,
            key: 'state',
            className:"ant-table-th-right pr8 va-t",
        }
        //只有一个过滤菜单的时候不显示
        if(filters.count() > 1){
            return orderColumns.concat([
                Object.assign(operation,{
                     filterDropdown: (
                        <div className="w100 bd" style={{backgroundColor: '#fff'}}>{_this.renderFilterButtons()}</div>
                    ),
                    filterIcon: <Icon type="down-circle-o"/>,
                    filterDropdownVisible: filterDropdownVisible,
                    onFilterDropdownVisibleChange: this.onFilterDropdownVisibleChange
                })
            ])
        }else{
            return orderColumns.concat([operation])
        }
        
    }
    /**
     * 过滤菜单按钮样式
     */
    renderFilterButtons = () => {
        //filters：所有的过滤选项
        //filterkeys：当前选中的过滤项，可能是多个选项，数组类型
        const {filters,filterKey} = this.props;

        return filters.toJS().map((status, index)=>{
            let {name, key} = status;
            let buttonCls = classNames('ml10 w80', {
                pusht: index == 0,
                pushb: filters.count() == index + 1,
                mt5: index != 0
            });
          
            return <Button 
                        key={key}
                        className={buttonCls}
                        onClick={()=>this.changeOrderStatus(key)}
                        type={key === filterKey ? "primary" : "ghost"}
                    >
                        {name}
                    </Button>
        })
    }

    changePageNum = (pageNum, pageSize) => {
        this.props.setPagination({pageNum})
        this.queryOrderList();
        this.scrollTop()
        
    }

    changePageSize = (current, pageSize) => {
        this.props.setPagination({pageNum:1,pageSize})
        this.queryOrderList();
        this.scrollTop()
    }
    scrollTop(){
        if(this.pageWrapper){
            this.pageWrapper.scrollTop = 0;
        }else if(window.document.getElementById("react-content")){
            window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0].scrollTop = 0;
        }
    }
    /**
     * 头部过滤菜单显示
     */
    onFilterDropdownVisibleChange = (visible) => {
         this.setState({
            filterDropdownVisible: visible
        })
    }

     /**
     * 切换不同订单状态列表
     * @param filterKey
     */
    changeOrderStatus = (filterKey) => {
        const {setOrderStatus, resetPagination} = this.props;
        setOrderStatus(filterKey);
        resetPagination();
        this.setState({
            filterDropdownVisible: false
        });
        this.queryOrderList();
    }
    /**
     * 列渲染
     * @returns {string|Buffer|Array.<T>|*|{options, browsertest, dist, rhino, rhinolessc}}
     */
    renderSubColumns() {
        const {type} = this.props;
        //详情页链接
        let detailLink = this.detailLink;
        // if(this.context.role){
        //     if(this.context.role.bname === roleEnum.CustomerService){
        //         //订单客服
        //         detailLink = "/after/sales/detail/";
        //     }else if(this.context.role.bname === roleEnum.Accounting){
        //         //会计角色
        //         detailLink = "/after/sales/waitrefund/";
        //     }
        // }
        
        return orderColumns.concat([
            {
                title: '操作',
                width: 350,
                key: 'orderOpt',
                className: "ant-table-th-center pr8 va-t",
                render: (value, record, index) => {
                    const buttons = [];
                    if(type === 'auditing'){
                        //退货申请
                        if(record.orderStatus === 'AUDITING'){
                            buttons.push(
                                <Popconfirm placement="top" title={"您确定要拒绝该申请吗？"} onConfirm={()=>{this.auditOrder(false,record.applyId)}} okText="确定" cancelText="取消">
                                    <Button type="ghost" loading={this.state.loading && this.auditStatus=== false && this.activeRid=== record.applyId} className="pushl" >拒绝</Button>
                                </Popconfirm>,
                                <Popconfirm placement="top" title={"您确定要通过该申请吗？"} onConfirm={()=>{this.auditOrder(true,record.applyId)}} okText="确定" cancelText="取消">
                                    <Button type="primary" loading={this.state.loading && this.auditStatus=== true && this.activeRid=== record.applyId} className="pushl" >通过</Button>
                                </Popconfirm>
                            )
                        }
                    }else if(type === 'audited'){
                        //退货单
                        if(record.orderStatus == 'WAIT_RETURN'){
                            buttons.push(
                                <Popconfirm placement="top" title={"您确定要取消吗？"} onConfirm={()=>{this.cancelOrder(record.applyId)}} okText="确定" cancelText="取消">
                                    <Button type="ghost" loading={this.state.loading && this.auditStatus=== false && this.activeRid=== record.applyId} className="pushl" >取消</Button>
                                </Popconfirm>,
                                <Popconfirm placement="top" title={"您确定要收货吗？"} onConfirm={()=>{this.receivedGoods(record.applyId)}} okText="确定" cancelText="取消">
                                    <Button type="primary" loading={this.state.loading && this.auditStatus=== true && this.activeRid=== record.applyId} className="pushl" >收货</Button>
                                </Popconfirm>
                            )
                        }
                    }else if(type === 'waitrefund'){
                        //待退款
                        if(record.orderStatus === 'WAIT_REFUND'){
                            buttons.push(
                                <Button key="refund" type="primary" className="pushl"  onClick={()=>{this.popupRefundDialog(record.applyId,record.tid)}}>退款</Button>
                            )
                        }
                    }
                    return (
                        <div className="button-list t-right">
                            <Link to={detailLink+record.applyId}><Button type="ghost" className="pushl">查看详情</Button></Link>
                            {buttons}
                        </div>

                    )
                }
            }
        ])
    }
    /**
     * 弹出退款模态框
     */
    popupRefundDialog = (rid,tid) => {
        this.props.fetchRefundOrderInfo(rid);
        this.setState({
            refundVisible:true,
            refundOrder:{rid:rid,tid}
        });
    }
    //确认退款
    confirmRefund = (values) => {
        const {refundOrder} = this.state;

        return this.props.confirmRefund(values,refundOrder.tid,refundOrder.rid)
            .then((resp)=>{
                this.cancelRefund();
                return resp;
            })
            .catch((er)=>{
                return Promise.reject(er);
            })
    }
    /**
     * 取消退款,关闭模态框
     */
    cancelRefund = () => {
        this.setState({
            refundVisible:false,
            refundOrder:{},
        })
    }
    /**
     * 退货商品有问题，取消售后订单，不给退，结束退货
     * @param rid 服务单编号
     */
    cancelOrder = (rid) => {
        this.auditStatus = false;
        this.activeRid = rid
        this.setState({loading:true});
        
        this.props.cancelOrder(rid)
            .then(()=>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            })
            .catch(()=>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            })
    }

    /**
     * 签收退货
     */
    receivedGoods = (rid) =>{
        this.auditStatus = true;
        this.activeRid = rid
        this.setState({loading:true})
        this.props.receivedGoods(rid)
            .then(()=>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            })
            .catch(() =>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            });
    }

    /**
     * 订单状态对于不同操作
     * @returns {[XML,XML]}
     */
   /* renderOpts(record) {
        //const orderStatus = this.props.order.get('orderStatus');
        const orderStatus = record.orderStatus;
        let opts = [
            // <li><Button type="ghost">打印订单</Button></li>
            // , <li><Button type="ghost mt8">复制订单</Button></li>

        ];

        if (orderStatus === 'WAIT_PAY') {
            opts.push(<li><Button type="ghost mt8">取消订单</Button></li>);
        }

        if (orderStatus === 'WAIT_PAY' || orderStatus === 'SUCCESS') {
            opts.push(<li><Button type="ghost mt8">售后回复</Button></li>);
        }
         opts.push(<li><Link to={`/order/${record.tid}`}><Button type="ghost mt8">订单详情</Button></Link></li>);

        return opts;
    }
*/
    queryOrderList() {
        //this.setLoading(true);
        //查询订单列表
        this.props.queryOrderList().then(()=>{
           // this.setLoading(false);
        }).catch(()=>{
          //  this.setLoading(false);
        });
    }

    /**
     * 审核订单
     * true：审核通过
     * false：不通过
     * @param checkout boolean
     */
    auditOrder = (checkout,rid) => {
        this.auditStatus = checkout;
        this.activeRid = rid;
        this.setState({loading:true})
        this.props.auditOrder(checkout,rid)
            .then(()=>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            })
            .catch(() =>{
                this.setState({loading:false})
                this.auditStatus = ''
                this.activeRid = ''
            });
    }
}

export default AfterSalesContainer;